import router from "@/router/index.js";
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import {getToken} from "@/util/auth.js";
import {useLayoutStore} from "@/stores/layout/index.js";
import {useUserStore} from "@/stores/user/index.js";

router.beforeEach((to, from, next) => {
    NProgress.start();
    const token = getToken();
    // 1. 已登录但访问登录页，跳转首页
    if (token && to.path === '/login') {
        NProgress.done();
        return next('/');
    }
    // 2. 检查路由是否存在
    if (to.matched.length === 0) {
        NProgress.done();
        return next('/404');
    }
    //如果该路由不需要登录，放行
    if (!to.meta.requireAuth){
        NProgress.done();
       return  next();
    }
    // 4. 如果需要登录，但是没有登录，则跳转登录页
    if (to.meta.requireAuth && !token) {
        NProgress.done();
        console.log('未登录查看token',token);
        return next('/login');
    }
    const userStore = useUserStore();
    //如果登陆了，但是没有权限访问，则跳转403
    if (to.name!=='home' &&userStore.menus.indexOf(to.name)===-1){
        console.log('没有权限访问',to.name)
    }
    // 3. 处理layout路由的tab
    const isLayoutRoute = /^\/layout/.test(to.path);
    if (isLayoutRoute) {
        const layoutStore = useLayoutStore();
        let tab = {
            name: to.path,
            title: to.meta.title,
            isClosable: to.meta.isClosable
        };
        layoutStore.addTab(tab);
    }
    // 5. 正常放行
    NProgress.done();
    return next();
});
